<template>
    <header>
        <div class="l-content">
            <el-button @click="handleMenu" plain icon="el-icon-menu" size="mini"></el-button>
        </div>
        <div class="r-content">
            <el-dropdown trigger="click" size="mini">
                <span>
                    <img class="user" :src="userImg">
                </span>
                <el-dropdown-menu slot="dropdown">
                    <div class="login" v-if="loginStatus == true">
                        <el-dropdown-item><el-button type="text" @click="logout">退出</el-button></el-dropdown-item>
                        <el-dropdown-item><el-button type="text" @click="logout">修改密码</el-button></el-dropdown-item>
                    </div>
                    <div class="un-login" v-if="loginStatus == false">
                        <!--登录窗口开始-->
                        <el-dropdown-item><el-button type="text" @click="openLogin = true">登录</el-button></el-dropdown-item>
                        <!--登录窗口结束-->
                        <el-dropdown-item><el-button type="text" @click="openRegister = true">注册</el-button></el-dropdown-item>
                    </div>
                </el-dropdown-menu>
            </el-dropdown>
        </div>

        <!--登录弹窗-->
        <el-dialog
                title="登录"
                :visible.sync="openLogin"
                width="30%"
                :before-close="handleClose">
            <div class="login-form">
                <el-form v-bind:model="loginForm" v-bind:rules="rules" ref="loginFormRef" label-width="80px" class="login_form">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="loginForm.username" prefix-icon="el-icon-user-solid"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" type="password" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="角色" prop="role">
                        <el-radio v-model="loginForm.role" label="1">系统用户</el-radio>
                        <el-radio v-model="loginForm.role" label="2">管理员</el-radio>
                    </el-form-item>
                    <el-form-item class="form_btn">
                        <el-button type="primary" @click="submitForm('loginFormRef')">提交</el-button>
                        <el-button type="info" @click="resetForm('loginFormRef')">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>

        <!--注册弹窗-->
        <el-dialog
                title="注册"
                :visible.sync="openRegister"
                width="30%"
                :before-close="handleClose">
            <div class="login-form">
                <el-form v-bind:model="loginForm" v-bind:rules="rules" ref="registerFormRef" label-width="80px" class="login_form">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="loginForm.username" prefix-icon="el-icon-user-solid"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" type="password" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="角色" prop="role">
                        <el-radio v-model="loginForm.role" label="1">系统用户</el-radio>
                        <el-radio v-model="loginForm.role" label="2">管理员</el-radio>
                    </el-form-item>
                    <el-form-item class="form_btn">
                        <el-button type="primary" @click="registerForm('registerFormRef')">提交</el-button>
                        <el-button type="info" @click="resetForm('registerFormRef')">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
    </header>

</template>

<script>
    //axios
    import axios from 'axios'

    export default {
        name: "CommonHeader",
        data(){
            return {
                //游客头像
                userImg: require("../assets/image/user-default.jpg"),
                //弹窗，默认关闭
                openLogin: false,
                openRegister: false,
                openUpdatePwd: false,
                //登录表单数据绑定对象
                loginForm: {
                    username: '',
                    password: '',
                    role: ''
                },
                //表单验证规则对象
                rules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        //{min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        //{min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
                    ]
                },
                loginStatus: false //登录状态，默认未登录
            }
        },
        methods: {
            //控制菜单展开/关闭
            handleMenu(){
                this.$store.commit('collapseMenu')
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },

            //提交表单-登录
            submitForm(formName) {
                //表单校验，成功则调用登录接口
                this.$refs[formName].validate(async valid => {
                    if (valid) {
                        let params = {
                            username: this.loginForm.username,
                            pwd: this.loginForm.password
                            //md5加密
                            //password: this.$md5(this.loginForm.password),
                        }
                        var that = this;

                        //发送请求
                        /*
                            接口: 用户登录
                            请求地址: http://localhost:8881/producer/login
                            请求方法: post
                            请求参数: password（用户名，字符串），pwd（密码，字符串）
                            响应内容: 结果
                        */
                        axios({
                            method: 'post',
                            url: 'http://localhost:8881/producer/login',
                            data: params
                        }).then(function (response) {
                            var res = response.data;
                            if(res.code == 200){
                                that.$message.success('登录成功！');
                                //将token存储到localStorage
                                localStorage.setItem("token", res.data.token);
                                localStorage.setItem("role", that.loginForm.role);
                                that.loginStatus = true;
                                //关闭弹窗
                                that.openLogin = false;
                                //跳转页面
                                that.$router.push('/host')
                            }else{
                                that.$message.error('用户名或密码不正确！');
                            }
                        }).catch(function (error) {
                            that.$message.error('系统发生错误！');
                            console.log(error);
                        });
                    } else {
                        return false
                    }
                });
            },
            //提交表单-注册
            registerForm(formName) {
                //表单校验，成功则调用注册接口
                this.$refs[formName].validate(async valid => {
                    if (valid) {
                        let params = {
                            username: this.loginForm.username,
                            pwd: this.loginForm.password,
                            role: this.loginForm.role
                            //md5加密
                            //password: this.$md5(this.loginForm.password),
                        }
                        var that = this;

                        //发送请求
                        /*
                            接口: 用户注册
                            请求地址: http://localhost:8881/producer/register
                            请求方法: post
                            请求参数: password（用户名，字符串），pwd（密码，字符串）
                            响应内容: 结果
                        */
                        axios({
                            method: 'post',
                            url: 'http://localhost:8881/producer/register',
                            data: params
                        }).then(function (response) {
                            var res = response.data;
                            if(res.code == 200){
                                that.openRegister = false;
                                that.$message.success('注册成功，请登录！');
                                //跳转页面
                                that.$router.push('/guest/code')
                            }else{
                                that.$message.error('用户名已存在！');
                            }
                        }).catch(function (error) {
                            that.$message.error('系统发生错误！');
                            console.log(error);
                        });
                    } else {
                        return false
                    }
                });
            },
            //重置
            resetForm(formName) {
                this.$refs[formName].resetFields()
            },
            //登出
            logout(){
                var that = this;
                let token = localStorage.getItem('token');

                //发送请求
                /*
                    接口: 用户登出
                    请求地址: http://localhost:8881/producer/logout
                    请求方法: get
                    请求参数: 无
                    响应内容: 结果
                */
                axios({
                    method: 'get',
                    url: 'http://localhost:8881/producer/logout',
                    //params: {},
                    headers: {
                        token: token
                    }
                }).then(function (response) {
                    var res = response.data;
                    if(res.code == 200){
                        that.openRegister = false;
                        that.$message.success('登出成功！');
                        //跳转页面
                        localStorage.removeItem("token");
                        localStorage.removeItem("role");
                        that.loginStatus = false;
                        that.$router.push('/guest/code')
                    }else{
                        that.$message.error('登出失败！');
                    }
                }).catch(function (error) {
                    that.$message.error('系统发生错误！');
                    console.log(error);
                });
            }
        },
        created: function () {
            var role = localStorage.getItem("role");
            this.loginStatus = (role == 3) ? false : true;
        }
    }
</script>

<style lang="less" scoped>
    header{
        display: flex;
        height: 100%;
        /*左右靠边*/
        justify-content: space-between;
        /*上下居中*/
        align-items: center;
    }

    .l-content{
        display: flex;
        align-items: center;
        .el-button{
            margin-right: 20px;
        }
    }

    .r-content{
        .user{
            width: 40px;
            height: 40px;
            /*圆弧*/
            border-radius: 50%;
        }
    }
</style>